﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

public enum ECardState
{
	Still,
	Moving,
	TouchZoom,
}

public class UnitCard : MonoBehaviour {

	public ECardState cardState;
	public int slot;
	public int unitId;
	public string passive_skill;
	public int nPos;
	public int SID;
	public int nOrder;
	public bool isMeCard;
	public bool isBossCard;
	public bool isNPCCard;
	public bool bShouldMoveToActive;
	public GameObject unitDesc;
	public UISprite sprite;
	public UIUnitCard unitCardScript;
	//public TestCardAttack cardAttackScript;
	//public GameObject coolTimeObj;
	//UISprite coolTimeSprite;
	UIPanel panel;
	public GameObject activeCardFrame;
	public UILabel deactiveTurnLabel;
	public int remainTurn;
	public int maxDeactiveRemainTurn;
	public GameObject blackSlotObj;
//	public GameObject cardObj;
	public bool isAddedCard;
	public Transform myParent;
	//public GameObject fxElementWin;
	//public GameObject fxElementLose;
	public GameObject blackBox;
	public GameObject skeleton;
	public element elementType;
//	ParticleSystem destroyPs;
//	ParticleSystem winPs;
	
	GameObject deactiveCountDownPs;
	float deactiveCountDownPs_startSize;
	GameObject cardRebirth;
	public bool isActivated = true;
	
	float cardRebirthStartSize;
	float cardRebirthChildStartSize;
	public GameObject lockEffect;
	
	GameObject remainCountObj;
	public List<AbnormalType> abnormalList = new List<AbnormalType>();
	public string skill_notify_string;

	void Start()
	{
	}
	
	
	public void Init(int _slot, int sid)
	{
		SID = sid;
		slot = _slot;
		nPos = _slot;
	}
	public void SetSlot(int _nOrder, int _slot, CUnitData unitData)
	{
		unitId = unitData.id;
		passive_skill = unitData.passive_skill;
		CSkillData skillData = CSkillDataManager.Instance.FindSkillData(passive_skill);
		if(skillData!=null)
		{
			skill_notify_string = skillData.notify_string;
			foreach(CAbnormalConst ab in skillData.abnormalList)
			{
				glog.debug(_slot+" card abnormal "+ab.Type.ToString(), LOGCOLOR.GREEN);
				abnormalList.Add( ab.Type);
			}
		}
		else if( !string.IsNullOrEmpty(passive_skill) )
		{
			string[] param = new string[2];
			param[0] = "SkillData";
			param[1] = passive_skill;
			MessagePopup.window.ShowPopup(MESSAGEPOPUPTYPE.TableDataError, param, null);
		}
		nOrder = _nOrder;
		//glog.debug("setslot "+_slot);
		nPos = _slot;
		slot = _slot;
		
		elementType = unitData.element;
		//gameObject.transform.FindChild("Slot").gameObject.GetComponent<UILabel>().text = slot.ToString();
		//sprite = gameObject.transform.FindChild("Image").gameObject.GetComponent<UISprite>();
		//unitCardScript = gameObject.transform.FindChild("Image").gameObject.GetComponent<UIUnitCard>();
		unitCardScript = gameObject.GetComponent<UIUnitCard>();
		//cardAttackScript = gameObject.GetComponent<TestCardAttack>();
		//fxElementWin = gameObject.transform.FindChild("FX_ElementWin").gameObject;
		//fxElementLose = gameObject.transform.FindChild("FX_ElementLose").gameObject;
		blackBox = gameObject.transform.FindChild("BlackBox").gameObject;
		skeleton = gameObject.transform.FindChild("Skeleton").gameObject;
		cardRebirth = CardManager.Instance.MakeCardRebirth();
		cardRebirth.transform.parent = gameObject.transform;
		cardRebirth.transform.localPosition=Vector3.zero;
		cardRebirth.transform.localScale=Vector3.one;
		cardRebirth.SetActive(false);
		cardRebirthStartSize = cardRebirth.GetComponent<ParticleSystem>().startSize;
		foreach(Transform child in cardRebirth.transform)
		{
			ParticleSystem childps = child.gameObject.GetComponent<ParticleSystem>();
			cardRebirthChildStartSize = childps.startSize;
		}	
		
		remainCountObj = gameObject.transform.FindChild("RemainCount").gameObject;
		panel = gameObject.GetComponent<UIPanel>();
//		deactiveCountDownPs = gameObject.transform.FindChild("FX_Countdown").gameObject.GetComponent<ParticleSystem>();
//		deactiveCountDownPs_startSize = deactiveCountDownPs.startSize;
	//	
		
//		destroyPs = gameObject.transform.FindChild("Fx_CardDistroy").gameObject.GetComponent<ParticleSystem>();
//		destroyPs.startSize = destroyPs.startSize * CardManager.Instance.popPosLeft.localScale.x;
//		foreach(Transform child in destroyPs.gameObject.transform)
//		{
//			ParticleSystem ps = child.gameObject.GetComponent<ParticleSystem>();
//			ps.startSize = ps.startSize * CardManager.Instance.popPosLeft.localScale.x;
//		}
		
//		winPs = gameObject.transform.FindChild("FX_Win").gameObject.GetComponent<ParticleSystem>();
	//	winPs.startSize = winPs.startSize * CardManager.Instance.popPosLeft.localScale.x;		
		
//		unitDesc = gameObject.transform.FindChild("UnitDesc").gameObject;
//		unitCardScript.unitDescObj = unitDesc;
//		if(nOrder==2)
//		{
//			//
//		}
//		if( unitData!= null )
//		{
//			unitDesc.transform.FindChild("UnitName").GetComponent<UILabel>().text = unitData.name_kor;
//			if(unitData.passive_skillList.Count>0)
//			{
//				if(HudManager.Instance.IsLocalKorean() )
//				{
//					unitDesc.transform.FindChild("SkillName").GetComponent<UILabel>().text = unitData.passive_skillList[0].name_kor;
//					unitDesc.transform.FindChild("SkillDesc").GetComponent<UILabel>().text = unitData.passive_skillList[0].desc_kor;
//				}
//			}
//		}
		
		
//		cardObj = gameObject.transform.FindChild("card").gameObject;
		
		
		//coolTimeObj = gameObject.transform.FindChild("CoolTime").gameObject;
		
		
		//coolTimeSprite = coolTimeObj.GetComponent<UISprite>();
		//activeCardFrame = gameObject.transform.FindChild("ActiveCardFrame").gameObject;
		//deactiveTurnLabel = gameObject.transform.FindChild("DeactiveTurn").gameObject.GetComponent<UILabel>();
		//deactiveTurnLabel.gameObject.SetActive(false);
	}
	
	public void SetnPos(int nNewPos)
	{
		nPos = nNewPos;
	}
	
	public void StartGlow()
	{
	//	activeCardFrame.SetActive(true);
	//	activeCardFrame.GetComponent<ActiveCardFrameAlpha>().StartGlow();
	}
	
	public void StopGlow()
	{
	//	activeCardFrame.GetComponent<ActiveCardFrameAlpha>().StopGlow();
	}
	
	/*
	public void SetActivate(bool bActivate, int maxRemainTurn)
	{
		if(bActivate)
		{
//			sprite.color = new Color( 1.0f, 1.0f, 1.0f, 1.0f);
//			deactiveTurnLabel.gameObject.SetActive(false);
			
			
			//coolTimeObj.SetActive(false);
			if(isMeCard || isBossCard)
			{
				Hashtable ht = iTween.Hash("from",coolTimeSprite.fillAmount, "to", 0 ,"time",1.0f, "delay", 0,  "onupdate","ChangeUpdate");
				iTween.ValueTo(gameObject,ht);
			}
			else
				coolTimeObj.SetActive(false);
				
		}
		else
		{
			glog.debug("Set Deactivate card "+slot+"  maxRemainTurn="+maxRemainTurn);
//			sprite.color = new Color( 0.4f, 0.4f, 0.4f, 1.0f);
			coolTimeObj.SetActive(true);
			coolTimeObj.GetComponent<UISprite>().fillAmount = 1.0f;
			maxDeactiveRemainTurn = maxRemainTurn;
		}
	}*/
	
	public void SetActivate(bool bActivate, int maxRemainTurn)
	{
		if(bActivate)
		{
			if(!isActivated)
			{
				cardRebirth.SetActive(true);
				ParticleSystem ps = cardRebirth.GetComponent<ParticleSystem>();
				ps.startSize = cardRebirthStartSize * gameObject.transform.localScale.x * gameObject.transform.parent.localScale.x;
				foreach(Transform child in cardRebirth.transform)
				{
					ParticleSystem childps = child.gameObject.GetComponent<ParticleSystem>();
					childps.startSize = cardRebirthChildStartSize * gameObject.transform.localScale.x * gameObject.transform.parent.localScale.x;
				}				
				cardRebirth.GetComponent<ParticleSystem>().Play();
			}
			isActivated = true;	
			remainCountObj.SetActive(false);
			blackBox.SetActive(false);
			skeleton.SetActive(false);
			//deactiveCountDownPs.Clear();
			//Destroy(deactiveCountDownPs);
		}
		else
		{
			isActivated = false;
			glog.debug("Set Deactivate card "+slot+"  maxRemainTurn="+maxRemainTurn);
			blackBox.SetActive(true);
			skeleton.SetActive(true);
			maxDeactiveRemainTurn = maxRemainTurn;
			SetDeactiveRemainTurn(maxDeactiveRemainTurn);
		}
	}
	
	public void SetDeactiveRemainTurn(int turn)
	{
		remainTurn = turn;
		if(turn==0)
		{
			SetActivate(true,0);
		}
		else
		{
			if(gameObject.activeSelf)
				StartCoroutine( "CoRemainCount");
						
		}
	}
	
	IEnumerator CoRemainCount()
	{
		remainCountObj.SetActive(false);
		yield return new WaitForSeconds(0.05f);
		remainCountObj.GetComponent<UILabel>().text = remainTurn.ToString();
		remainCountObj.SetActive(true);
	}
	
	IEnumerator CoDeactiveCountDownPs()
	{
		//Debug.LogError("CoDeactiveCountDownPs  "+slot);
		Destroy(deactiveCountDownPs);
		deactiveCountDownPs = NGUITools.AddChild( gameObject, CardManager.Instance.fxDeactiveCountPrefab);
		deactiveCountDownPs.transform.localPosition = CardManager.Instance.fxDeactiveCountPrefab.transform.localPosition;
		ParticleSystem ps = deactiveCountDownPs.GetComponent<ParticleSystem>();
		//deactiveCountDownPs.gameObject.SetActive(true);
		//deactiveCountDownPs.Clear();
		yield return null;
		int index = 9 - remainTurn;
		
		//deactiveCountDownPs.startSize = deactiveCountDownPs_startSize;
		//float startSize = ps.startSize;
		float parentSize = gameObject.transform.localScale.x;
		float parentParentSize = gameObject.transform.parent.localScale.x;
		ps.startSize = ps.startSize * parentSize * parentParentSize;
		
		ps.renderer.material.mainTexture = UIManager.Instance.textureCount[index];
		ps.Play ();		
		yield return new WaitForSeconds(1.5f);
		ps.Pause ();
		
	}

	public void CreateCardLock()
	{
		if(CardManager.Instance.cardLockPrefab==null)
			CardManager.Instance.cardLockPrefab = Resources.Load ("Prefabs/FX/FX_CardLocked") as GameObject;
		if(lockEffect == null) {
			lockEffect = NGUITools.AddChild(gameObject, CardManager.Instance.cardLockPrefab);
			lockEffect.transform.localPosition = CardManager.Instance.cardLockPrefab.transform.position;
			lockEffect.transform.localRotation = CardManager.Instance.cardLockPrefab.transform.rotation;
			lockEffect.transform.localScale = CardManager.Instance.cardLockPrefab.transform.localScale;
		}
	}

	/*
	public void SetDeactiveRemainTurn(int turn)
	{
//		if(deactiveTurnLabel==null)
//			return;
//		deactiveTurnLabel.gameObject.SetActive(true);
		remainTurn = turn;
//		deactiveTurnLabel.text = "turn "+remainTurn;
		
		float fill = (float)turn/(float)maxDeactiveRemainTurn;
		Hashtable ht = iTween.Hash("from",coolTimeSprite.fillAmount, "to", fill ,"time",1.0f, "delay", 0,  "onupdate","ChangeUpdate");
		iTween.ValueTo(gameObject,ht);
		
		//coolTimeObj.GetComponent<UISprite>().fillAmount = (float)turn/(float)maxDeactiveRemainTurn;
	}
	
	void ChangeUpdate(float newValue)
	{
		//glog.debug("coolTimeSprite  "+newValue);
		coolTimeSprite.fillAmount = newValue;
		if(newValue==0)
			coolTimeObj.SetActive(false);
	}*/	
	
	public void SetDisableCardScaleChange(bool bEnable, float restoreTimeDelay)
	{
		//unitCardScript.SetDisableAndRestore(restoreTimeDelay);
	}
	
	public void ShowCardDestrory()
	{
		if(!gameObject.activeSelf)
			return;
		//GameObject go = CardManager.Instance.GetCardDestroyFX(gameObject);

		GameObject go = CardManager.Instance.MakeDestroyEffect(transform);

		//GameObject go = Instantiate(CardManager.Instance.fxCardDestroyPrefab) as GameObject;
		//go.transform.parent = transform;
		//go.transform.localPosition = CardManager.Instance.fxCardDestroyPrefab.transform.localPosition;
		//go.transform.localScale = CardManager.Instance.fxCardDestroyPrefab.transform.localScale;

		//CardManager.Instance.ScaleChangeCardDestroyFX();
		//go.SetActive(true);
		//CardManager.Instance.fxCardDestroyPS.Play();
		SoundManager.Instance.PlaySound(44);

		CardManager.Instance.ClearDestroyEffect(go,gameObject);
		//StartCoroutine( SeperateCardDestroyFx(go));
	}
	
	IEnumerator SeperateCardDestroyFx(GameObject go)
	{
		yield return new WaitForSeconds(1.0f);
		SoundManager.Instance.PlaySound(45);
		//go.transform.parent = CardManager.Instance.centerAnchor.transform;
		//Destroy(go);
		//go.transform.parent = CardManager.Instance.transform;
		CardManager.Instance.ReleaseDestroyEffect(go);
		gameObject.SetActive(false);
	}
	
	public void ShowWinEffect()
	{	
		GameObject goEff = CardManager.Instance.fxWinObj;
		goEff.transform.parent = gameObject.transform;
		goEff.transform.localPosition = CardManager.Instance.fxWinPrefab.transform.localPosition;
		goEff.transform.localScale = CardManager.Instance.fxWinPrefab.transform.localScale;
		CardManager.Instance.fxWinPS.Play();

		StartCoroutine( CoDetachWinObj(goEff) );

		//winPs.startSize = winPs.startSize * CardManager.Instance.popPosLeft.localScale.x;
//		StartCoroutine( MoveWinFx(goEff));
	}

	IEnumerator CoDetachWinObj(GameObject goEff)
	{
		yield return new WaitForSeconds(2.0f);
		goEff.transform.parent = null;
	}
	
	IEnumerator MoveWinFx(GameObject goEff)
	{
		yield return new WaitForSeconds(1.0f);
		
		//Vector3 newPos = goEff.transform.localPosition;
		//newPos.y += 200;
		//iTween.MoveTo( goEff, iTween.Hash("time", 0.1f, "position", newPos,  "islocal", true, "easetype","linear" )  );
		
		goEff.SetActive(false);
		//Destroy(goEff,1.0f);
	}	
	
	void SetElementTexture(GameObject go)
	{
		GameObject rockPaper = go.transform.FindChild("RockPaperScissors").gameObject;
		int i=0;
		if(elementType == element.earth)
			i=1;
		else if(elementType == element.sky)
			i=2;
		//go.GetComponent<ParticleSystem>().renderer.material.mainTexture = CardManager.Instance.elementWinTexture[i];
		rockPaper.GetComponent<ParticleSystem>().renderer.material.mainTexture = CardManager.Instance.elementRockPaperTexture[i];
	}
	
	public void PlayElementFX(int opponentSID, float delay, bool isWinner)
	{
		RemoveElementLoseDimmed();
		StartCoroutine( CoPlayElementFX(opponentSID, delay, isWinner) );
	}
	
	IEnumerator CoPlayElementFX(int opponentSID, float delay, bool isWinner)
	{
		yield return new WaitForSeconds(delay + IngameSetting.Instance.PopCardDelay);
		
		if( CardManager.Instance.HasCurActiveCard(opponentSID) )
		{
			GameObject fxObject = null;
			GameObject goElementEff = null;

			//CardManager.Instance.MakeFXElementWinLose();

			if(isWinner)	{
				glog.debug("winner element fx");


//				SetElementTexture(CardManager.Instance.fxElementWin);
//				fxObject = CardManager.Instance.fxElementWin;
//				fxObject.transform.parent = transform;
//				fxObject.transform.localPosition = Vector3.zero;
//				fxObject.transform.localScale = CardManager.Instance.prefab_fxElementWin.transform.localScale;
//
//				fxObject.SetActive(true);
				goElementEff = CardManager.Instance.ShowElementEffect_Win(gameObject, SID, opponentSID );

				SoundManager.Instance.PlaySound(43);
			}
			else {
			/*	SetElementTexture(CardManager.Instance.fxElementLose);
				fxObject = CardManager.Instance.fxElementLose;
				fxObject.transform.parent = transform;
				fxObject.transform.localPosition = Vector3.zero;
				fxObject.transform.localScale = CardManager.Instance.prefab_fxElementWin.transform.localScale;
				*/
				//yield return new WaitForSeconds(0.1f);


				//blackBox.SetActive(true);
				goElementEff = CardManager.Instance.ShowElementEffect_Lose(gameObject, SID, opponentSID );

			}

			yield return new WaitForSeconds(1.0f);
			if(!isWinner)
				blackBox.SetActive(true);
			yield return new WaitForSeconds(0.4f);
			if(goElementEff!=null)
				CardManager.Instance.ReleaseElementEffect(goElementEff);
			CardManager.Instance.isElementFX = false;
			//if(fxObject!=null) {
			//	fxObject.transform.parent=CardManager.Instance.transform;
			//}

		}
		else
			CardManager.Instance.isElementFX = false;
	}

	public void RemoveElementLoseDimmed()
	{
		blackBox.SetActive(false);
	}
	
	public void ChangeDepth(float time , int nTarget)
	{
		
		if(false)//time>0.1f)
		{
			if(IngameSetting.Instance.cardTween == CardTweenType.LeanTween)
			{
				LeanTween.value( gameObject, updateValueCallback, (float)( panel.depth) , (float)(CardManager.Instance.originalDepth - nTarget), time-0.1f);
			}
			else
			{
				Hashtable ht = iTween.Hash("from", (float)( panel.depth) , "to", (float)(CardManager.Instance.originalDepth - nTarget) ,"time",time-0.1f,  "onupdate","ChangeUpdateDepth");
				iTween.ValueTo(gameObject,ht);
			}
		}
		else
			panel.depth = CardManager.Instance.originalDepth - nTarget;
	}
	
	
	public void updateValueCallback( float val, object hash ){
		// Hashtable h = hash as Hashtable;
		// Debug.Log("message:"+h["message"]+" val:"+val);
		panel.depth = (int)val;
	}
	
	
	void ChangeUpdateDepth(float newValue)
	{
		//glog.debug(gameObject.name+ "  newBalue="+newValue);
		panel.depth = (int)newValue;
	}	
	
	
	public void SetPositionDeactiveCard_OtherPlayer(int sid, float time)
	{
		if(gameObject.activeSelf)
			StartCoroutine(CoSetPositionDeactiveCard_OtherPlayer(sid, time) );
		else
			CardManager.Instance.MoveNextCardPos_OtherPlayer(sid, this, 0,"");
	}
	
	IEnumerator CoSetPositionDeactiveCard_OtherPlayer(int sid, float time)
	{
		yield return new WaitForSeconds(time);
		
		CardManager.Instance.MoveNextCardPos_OtherPlayer(sid, this, 0,"");

	}

	public void SetForceMovingState()
	{
		SetForceMovingState(-1);// don't back to ECardState.Still state 
	}

	public void SetForceMovingState(float delayBackToStill)
	{
		if(cardState== ECardState.TouchZoom)
		{
			unitCardScript.StopTouchZoom();
		}
		cardState = ECardState.Moving;
		if(delayBackToStill>0)
			StartCoroutine("CoGoToStillState",delayBackToStill);
		else if(delayBackToStill==0)
			cardState= ECardState.Still;
	}

	IEnumerator CoGoToStillState(float delay)
	{
		yield return new WaitForSeconds(delay);
		cardState= ECardState.Still;
	}

	public void SetStillState()
	{
		cardState= ECardState.Still;
	}
}
